<template>
  <div class="pagelist">
    <span title="Total record"
      >&nbsp;<b>第{{ pages ? pages : 1 }}/{{ cur_page }}页</b></span
    >
    <template v-for="(p, i) in btns">
      <strong
        v-if="p.page != cur_page"
        :key="i"
        @click="change_event(p.page)"
        >{{ p.title }}</strong
      >
      <b v-else :key="i">{{ p.title }}</b>
    </template>
  </div>
</template>
<script>
export default {
  props: ["pages", "page"],
  data() {
    return {
      cur_page: 1,
      max_len: 8,
    };
  },
  watch: {
    page() {
      this.cur_page = this.page * 1;
    },
  },
  created() {
    this.cur_page = this.page * 1;
  },
  computed: {
    btns() {
      //分页处理
      const ar = [];
      if (this.pages <= this.max_len) {
        for (let i = 1; i <= this.pages; i++) {
          ar.push({
            page: i,
            title: i,
          });
        }
        return ar;
      }
      let more = Math.ceil(this.max_len / 3);

      ar.push({
        page: 1,
        title: "首页",
      });
      for (let i = 2; i < this.pages; i++) {
        //左边
        if (i >= this.cur_page - more && i < this.cur_page) {
          ar.push({
            page: i,
            title: i,
          });
        } else if (i < this.cur_page + more + 1 && i >= this.cur_page) {
          //右边
          ar.push({
            page: i,
            title: i,
          });
        }
      }
      //截断
      if (ar[1].page > more) {
        ar[1].title = "...";
      }
      if (ar[ar.length - 1].page < this.pages - 1) {
        ar[ar.length - 1].title = "...";
      }

      ar.push({
        page: this.pages,
        title: "尾页",
      });

      return ar;
    },
  },
  methods: {
    change_event(page) {
      this.cur_page = page;
      this.$emit("change_event", page);
    },
  },
};
</script>